package com.sixbing.spider.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sixbing.spider.bean.MessageBean;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ResponseUtils {
    public static void Response(HttpServletResponse response, Object obj) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(getSuccessBean(obj)));
        response.getWriter().close();
    }

    public static void ResponseError(HttpServletResponse response) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(getErrorBean()));
        response.getWriter().close();
    }

    public static void ResponseError(HttpServletResponse response, int code, String message) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        response.getWriter().write(mapper.writeValueAsString(getErrorBean(code, message)));
        response.getWriter().close();
    }

    private static MessageBean getErrorBean(int code, String message) {
        return new MessageBean(code, message, code == 200 ? true : false, "");
    }

    private static MessageBean getSuccessBean(Object obj) {
        return new MessageBean(200, "请求成功", true, obj);
    }

    private static MessageBean getErrorBean() {
        return getErrorBean(400, "后端未知错误");
    }

}
